﻿using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.DesignServer.ServiceImplement;
using CPPEI.Coolzon.Server.ServiceImplement;
using CPPEI.Coolzon.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.Coolzon.DesignServer
{
    class Program
    {
        private static ServiceHost s_designServiceHost;
        private static ServiceHost s_dataServiceHost;

        static void Main(string[] args)
        {
            Logger.InitByLogDirectory(string.Format("{0}\\Coolzon\\Logs\\Server", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)));

            LoadHostConfig();

            //初始化文件存储服务的存储地址
            CPPEI.Coolzon.Runtime.Metadata.Storage.InitWithDirectory("c:\\Coolzon\\v1.5.x\\DesignServer\\RuntimeStorage\\");
            CPPEI.Coolzon.Designtime.Metadata.Storage.InitWithDirectory("c:\\Coolzon\\v1.5.x\\DesignServer\\DesigntimeStorage\\");

            HostDesignService();
            HostDataService();
            
            InputLoop();

            StopDataService();
            StopDesignService();

            Logger.Info("Server", "服务器关闭");
        }
        private static void LoadHostConfig()
        {
            Logger.InfoToTag("Server", "加载Host配置信息...");
            try
            {
                CPPEI.Coolzon.Configuration.Server.Config.InitHostConfig(CZEnvironment.GetHostConfigFilePath());
                Logger.InfoToTag("Server", "加载Host配置信息完毕!");
            }
            catch
            {
                Logger.Error("Server", "加载Host配置信息出错!");
            }
        }

        private static void HostDesignService()
        {
            Logger.InfoToTag("Server", "设计服务启动中...");
            Configuration.Server.ServiceConfig serviceConfig = Configuration.Server.Config.Host.GetServiceConfig("DesignService");
            Uri baseAddress = new Uri(string.Format("net.tcp://{0}:{1}/{2}/", serviceConfig.IP, serviceConfig.Port, serviceConfig.Path));

            s_designServiceHost = new ServiceHost(typeof(DesignService), baseAddress);

            Binding binding = new NetTcpBinding();
            (binding as NetTcpBinding).Security.Mode = SecurityMode.None;
            (binding as NetTcpBinding).TransferMode = TransferMode.Streamed;
            (binding as NetTcpBinding).ReceiveTimeout = TimeSpan.FromSeconds(300);
            (binding as NetTcpBinding).SendTimeout = TimeSpan.FromSeconds(300);
            (binding as NetTcpBinding).MaxBufferSize = 1 * 1024 * 1024 * 1024;
            (binding as NetTcpBinding).MaxReceivedMessageSize = 1 * 1024 * 1024 * 1024;
            ServiceMetadataBehavior serviceMetadataBehavior = new ServiceMetadataBehavior();
            s_designServiceHost.Description.Behaviors.Add(serviceMetadataBehavior);

            if (serviceConfig.MetadataGet)
            {
                Logger.InfoToTag("Server", "设计服务元数据获取开关:开启");
                Logger.Info("Server", "设计服务元数据获取地址:{0}mex", baseAddress);
                s_designServiceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex");
            }
            else
            {
                Logger.InfoToTag("Server", "设计服务元数据获取开关:关闭");
            }

            s_designServiceHost.AddServiceEndpoint(typeof(IDesignService), binding, baseAddress);
            Logger.InfoToTag("Server", "设计服务地址:{0}", baseAddress);

            try
            {
                s_designServiceHost.Open();
                Logger.InfoToTag("Server", "设计服务启动成功");
            }
            catch (Exception ex)
            {
                Logger.ErrorToTag("Server", string.Format("设计服务启动失败{0}{1}", Environment.NewLine, ex));
            }
        }

        private static void HostDataService()
        {
            Logger.InfoToTag("Server", "数据服务启动中...");
            Configuration.Server.ServiceConfig serviceConfig = Configuration.Server.Config.Host.GetServiceConfig("DataService");
            Uri baseAddress = new Uri(string.Format("net.tcp://{0}:{1}/{2}/", serviceConfig.IP, serviceConfig.Port, serviceConfig.Path));

            s_dataServiceHost = new ServiceHost(typeof(CPPEI.Coolzon.ServiceImp.DataService), baseAddress);
            Binding binding = new NetTcpBinding();
            (binding as NetTcpBinding).ReceiveTimeout = TimeSpan.FromSeconds(300);
            (binding as NetTcpBinding).SendTimeout = TimeSpan.FromSeconds(300);
            (binding as NetTcpBinding).Security.Mode = SecurityMode.None;
            ServiceMetadataBehavior serviceMetadataBehavior = new ServiceMetadataBehavior();
            s_dataServiceHost.Description.Behaviors.Add(serviceMetadataBehavior);

            ServiceThrottlingBehavior serviceThrottlingBehavior = new ServiceThrottlingBehavior();
            serviceThrottlingBehavior.MaxConcurrentSessions = 10000;
            serviceThrottlingBehavior.MaxConcurrentCalls = 10000;
            serviceThrottlingBehavior.MaxConcurrentInstances = 20000;
            s_dataServiceHost.Description.Behaviors.Add(serviceThrottlingBehavior);

            if (serviceConfig.MetadataGet)
            {
                Logger.InfoToTag("Server", "数据服务元数据获取开关:开启");
                Logger.InfoToTag("Server", "数据服务元数据获取地址:{0}mex", baseAddress);
                s_dataServiceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex");
            }
            else
            {
                Logger.InfoToTag("Server", "数据服务元数据获取开关:关闭");
            }

            s_dataServiceHost.AddServiceEndpoint(typeof(IDataService), binding, baseAddress);
            Logger.InfoToTag("Server", "数据服务地址:{0}", baseAddress);

            try
            {
                s_dataServiceHost.Open();
                Logger.InfoToTag("Server", "数据服务启动成功");
            }
            catch (Exception ex)
            {
                Logger.Error("Server", string.Format("数据服务启动失败{0}{1}", Environment.NewLine, ex));
            }
        }

        private static void StopDesignService()
        {
            Logger.InfoToTag("Server", "设计服务关闭中...");
            try
            {
                s_designServiceHost.Close();
                Logger.InfoToTag("Server", "设计服务关闭成功");
            }
            catch (Exception ex)
            {
                Logger.ErrorToTag("Server", string.Format("设计服务关闭失败{0}{1}", Environment.NewLine, ex));
            }
        }

        private static void StopDataService()
        {
            Logger.InfoToTag("Server", "数据服务器关闭中...");
            try
            {
                s_dataServiceHost.Close();
                Logger.InfoToTag("Server", "数据服务关闭成功");
            }
            catch (Exception ex)
            {
                Logger.ErrorToTag("Server", string.Format("数据服务关闭失败{0}{1}", Environment.NewLine, ex));
            }
        }

        private static void InputLoop()
        {
            string cmd = Console.ReadLine().ToUpper();
            while (cmd != null)
            {
                if (cmd == "EXIT")
                {
                    break;
                }
                else
                {
                    cmd = Console.ReadLine().ToUpper();
                }
            }
        }

    }
}
